<?php

namespace App\Http\Controllers\Api;

use App\Models\Renting;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class LoginController extends Controller
{
    //
    public function login(Request $request)
    {
        try{
            $this->validate($request,[
               'username'=>'required',
                'password'=>'required'
            ]);
        }catch (\Exception $e){
            return ['status'=>1000,'msg'=>'账号或密码不能为空'];
        }
        //查看对象中的可用方法
//        dd(get_class_methods())
        $bool = auth()->guard('apiweb')->attempt($request->all());
        //登录成功
        if($bool){
            //生成token
            //得到用户模型对象
            $userModel = auth()->guard('apiweb')->user();
            //判断接口当天是否超过2000次
            if($userModel->click > env('APINUM')){
                return response()->json(['status'=>1002,'msg'=>'当天接口请求超过'],500);
            }
            $token = $userModel->createToken('api')->accessToken;
            //当前请求次数加1 数据一致
            $userModel->increment('click');
            $data = [
              'expire'=>7200,
              'token'=>$token
            ];
            return response()->json($data);

        }else{
            return response()->json(['status'=>1001,'msg'=>'账号或者密码不正确'],401);
        }
    }

    //小程序微信登录
    public function wxlogin(Request $request)
    {
        $appid = 'wx43185ffb7261ba89';
        $secret = 'da046e36060b8cac143e1d042ca7515b';
        //小程序传过来
        $code = $request->get('code');
        // 请求地址
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code';
        $url = sprintf($url, $appid, $secret, $code);

      //verify 不检查整数ssl
        $client = new Client(['timeout'=>5,'verify'=>false]);
        $response = $client->get($url);
        $json = (string)$response->getBody();

        $arr = json_decode($json,true);

        //写入数据库
        try{
            Renting::create(['openid'=>$arr['openid']]);
        }catch (\Exception $e){

        }
        return $json;


    }
}
